/*
 * @Author: yangzonglong
 * @Date: 2021-03-01 13:18:46
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-09-20 17:34:23
 * @Auditor:
 */
import React, { useMemo, useRef, useImperativeHandle, useState, useEffect } from 'react';
import { ActionText } from '@library';
import ModalForm from './_ModalForm';
import Qs from 'query-string';
import evalScriptText from './../../../eval';
import { ModalFormRef } from './interface';
import { ActionFieldType } from './../../../interface';
interface RefProps {
  getData(): any;
}

const App = (props: any, ref: React.Ref<RefProps>) => {

  const query = Qs.parseUrl(window.location.href).query;
  const { enviromentConfig, columns, _dataIndex, value, disabled } = props;
  const [v, setV] = useState({});
  const modalFormRef = useRef<ModalFormRef>(null);

  useEffect(() => {
    setV(Array.isArray(value) ? { list: value } : value || {});
  }, [value]);

  const _options = useMemo(() => {
    if (Array.isArray(columns) && _dataIndex) {
      const _item = columns.filter(item => item.dataIndex === _dataIndex);
      return _item?.[0] || { options: {} };
    } else {
      return { options: {} };
    }

  }, [columns, _dataIndex]);

  const onClick = async () => {
    const values = await props.validateFields(props.options?.required ?? false, undefined, false);
    
    if (_options.options.scriptText) {
      const refsKey = Object.keys(props.controlRefs as any);
      const refDataList: any = [];

      if (refsKey.length) {
        for (let item of refsKey) {
          if (props.controlRefs?.[item]?.onListRefresh) {
            refDataList.push(props.controlRefs?.[item]);
          }
        }
      }
      
      const _OBJ1_ = { ...values, _RECORD_: props.record, _HEAD_: values };

      evalScriptText({
        scriptText: _options.options.scriptText,
        extra: {
          _OBJ1_,
          _OBJ_: props.record,
          _ENV_: enviromentConfig || {},
          _REFS_: refDataList,
          _QUERY_: query,
          showModal: (options: any) => props.showModal({
            ...options,
            initValue: { ...options.initValue, _RECORD_: props.record }
          })
        },
        next: (result: any, actionFiled?: ActionFieldType) => {
          props?.onValuesChange((props._id || props.id)!, result || {}, true);

          if (actionFiled) {
            props?.setActionFiledMap?.((prev: ActionFieldType) => {
              return { ...prev, ...actionFiled };
            });
          }
        }
      });
    } else {
      modalFormRef?.current?.show?.(
        typeof v === 'object' ?
          { ...v, _RECORD_: props.record, _HEAD_: values, hide: modalFormRef?.current.hide }
          :
          { _RECORD_: props.record, _HEAD_: values },
        _options.options.formName!,
        '',
        _options.disabled || disabled
      );
    }
  };

  useImperativeHandle(ref, () => ({
    getData() {
      return v;
    },
  }));

  return (
    <>
      {!props.record[`${_options.dataIndex}_disabled`] && (
        <ActionText.Detail onClick={onClick}>{_options.options.actionText}</ActionText.Detail>
      )}
      <ModalForm formName={_options.options.formName} ref={modalFormRef} callback={setV} />
    </>
  );
};

export default App;
